/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.github.tbouron.shakedetector.example.slice;

import com.github.tbouron.shakedetector.example.LogUtils;
import com.github.tbouron.shakedetector.example.ResourceTable;
import com.github.tbouron.shakedetector.library.ShakeDetector;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.animation.AnimatorProperty;
import ohos.agp.components.AttrHelper;
import ohos.agp.components.Component;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.Slider;
import ohos.agp.components.Text;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.utils.Point;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.dialog.ToastDialog;
import ohos.agp.window.service.Display;
import ohos.agp.window.service.DisplayManager;
import ohos.app.Context;
import ohos.media.image.Image;

import java.text.SimpleDateFormat;
import java.util.Date;

import static com.github.tbouron.shakedetector.example.LogUtils.DEBUG;
import static com.github.tbouron.shakedetector.example.LogUtils.ERROR;
import static com.github.tbouron.shakedetector.example.LogUtils.FIVETY;
import static com.github.tbouron.shakedetector.example.LogUtils.FOUR;
import static com.github.tbouron.shakedetector.example.LogUtils.NUM2085;
import static com.github.tbouron.shakedetector.example.LogUtils.WUBAI;

/**
 * 主页面
 *
 * @since 2021-03-20
 */
public class MainAbilitySlice extends AbilitySlice {
    private float sensibilitys;
    private Image image;
    private boolean isFlag = false;
    private CommonDialog mCommonDialog = null;
    private Text textStatus;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        initView();
        ShakeDetector.create(this, new ShakeDetector.OnShakeListener() {
            @Override
            public void OnShake() {
                    addStatusMessage("shake_detected");
                    new ToastDialog(getContext())
                            .setText("Device shaken!")
                            .setAlignment(LayoutAlignment.BOTTOM)
                            .setTransparent(true)
                            .setAutoClosable(true)
                            .show();
            }
        });
        if (ShakeDetector.start()) {
            sensibilitys = ShakeDetector.DEFAULT_THRESHOLD_ACCELERATION;
            addStatusMessage(getString(ResourceTable.String_app_name));
            ShakeDetector.updateConfiguration(sensibilitys, ShakeDetector.DEFAULT_THRESHOLD_SHAKE_NUMBER);
        } else {
            LogUtils.log(DEBUG, "test", "初始化失败");
        }
    }

    /**
     * 初始化
     */
    private void initView() {
        textStatus = (Text) findComponentById(ResourceTable.Id_text_status);
        findComponentById(ResourceTable.Id_menu).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                Display display = DisplayManager.getInstance().getDefaultDisplay(getAbility()).get();
                int width = display.getAttributes().width;
                int height = display.getAttributes().height;
                mCommonDialog = new CommonDialog(getAbility());
                Component component1 = LayoutScatter.getInstance(getContext())
                        .parse(ResourceTable.Layout_layout_x, null, true);
                initComponent(component1);
                int statusHeight = getStatusBarHeight(getAbility()) / DEBUG;
                int margin = AttrHelper.vp2px(FIVETY, getAbility());
                int margin2 = AttrHelper.vp2px(FOUR, getAbility());
                mCommonDialog.setSize(width / LogUtils.SAN * LogUtils.TWO, height - statusHeight - margin);
                mCommonDialog.setContentCustomComponent(component1);
                mCommonDialog.setAutoClosable(true);
                mCommonDialog.setTransparent(true);
                if (height > NUM2085) {
                    mCommonDialog.setOffset(0, (statusHeight + margin) / LogUtils.TWO);
                } else {
                    mCommonDialog.setOffset(0, margin2);
                }
                mCommonDialog.setAlignment(LayoutAlignment.RIGHT);
                AnimatorProperty property = createanimbottom();
                property.setTarget(component1);
                mCommonDialog.show();
                property.start();
            }
        });
    }

    /**
     * 初始化
     *
     * @param component1 Component
     */
    private void initComponent(Component component1) {
        final Text sensibilityLabel = (Text) component1.findComponentById(ResourceTable.Id_sensibility_label);
        Slider sensibility = (Slider) component1.findComponentById(ResourceTable.Id_sensibility);
        final Text shakeNumberLabel = (Text) component1.findComponentById(ResourceTable.Id_shake_number_label);
        Slider shakeNumber = (Slider) component1.findComponentById(ResourceTable.Id_shake_number);
        sensibility.setProgressValue((int) ShakeDetector.mThresholdAcceleration / LogUtils.SISHI);
        shakeNumber.setProgressValue(ShakeDetector.mThresholdShakeNumber);
        updateSeekBarLabel(sensibilityLabel, ShakeDetector.mThresholdAcceleration / LogUtils.SIBAI);
        updateSeekBarLabel(shakeNumberLabel, ShakeDetector.mThresholdShakeNumber);

        sensibility.setValueChangedListener(new Slider.ValueChangedListener() {
            @Override
            public void onProgressUpdated(Slider slider, int progress, boolean isFromUser) {
                if (isFromUser) {
                    float sensibilityss = (float) (progress * LogUtils.SISHI);
                    ShakeDetector.updateConfiguration(sensibilityss, shakeNumber.getProgress());
                    updateSeekBarLabel(sensibilityLabel, (float) progress / LogUtils.SHI);
                    addStatusMessage("Update sensibility to:" + (float) progress / LogUtils.SHI + "G");
                }
            }

            @Override
            public void onTouchStart(Slider slider) {
            }

            @Override
            public void onTouchEnd(Slider slider) {
            }
        });
        shakeNumber.setValueChangedListener(new Slider.ValueChangedListener() {
            @Override
            public void onProgressUpdated(Slider slider, int progress, boolean isFromUser) {
                int progress2 = sensibility.getProgress();
                float sensibilityss = (float) (progress2 * LogUtils.SISHI);
                ShakeDetector.updateConfiguration(sensibilityss, progress);
                updateSeekBarLabel(shakeNumberLabel, progress);
                addStatusMessage("Update number of shakes to triggerto:" + progress);
            }

            @Override
            public void onTouchStart(Slider slider) {
            }

            @Override
            public void onTouchEnd(Slider slider) {
            }
        });
    }

    /**
     * updateSeekBarLabel
     *
     * @param view Text
     * @param textToAppend float
     */
    private void updateSeekBarLabel(Text view, float textToAppend) {
        if (view.getId() == ResourceTable.Id_sensibility_label) {
            view.setText("Sensibility:" + textToAppend + "G");
        } else {
            view.setText("Number of shakes:" + (int) textToAppend);
        }
    }

    /**
     * addStatusMessage
     *
     * @param message
     */
    private void addStatusMessage(String message) {
        String date = new SimpleDateFormat("HH:mm:ss-SSS").format(new Date());
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(System.lineSeparator());
        stringBuilder.append(date);
        stringBuilder.append(message);
        textStatus.append(stringBuilder.toString());
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    protected void onStop() {
        super.onStop();
        /**
         * 停止检测
         */
        ShakeDetector.stop();
        addStatusMessage("shake_detector_stopped");
        /**
         * 销毁实例
         */
        ShakeDetector.destroy();
        addStatusMessage("Listener Destroyed");
    }

    /**
     * 弹出动画
     *
     * @return AnimatorProperty
     */
    private AnimatorProperty createanimbottom() {
        Display display = DisplayManager.getInstance().getDefaultDisplay(getAbility()).get();
        int width = display.getAttributes().width;
        AnimatorProperty animator = new AnimatorProperty();
        animator.moveFromX(width).moveToX(0).alphaFrom(0).alpha(1).setDuration(WUBAI);
        return animator;
    }

    /**
     * 获取状态栏高度
     *
     * @param context context
     * @return 高度
     */
    public static int getStatusBarHeight(Context context) {
        int result = 0;
        Point point1 = new Point();
        Point point2 = new Point();
        Display display = DisplayManager.getInstance().getDefaultDisplay(context).get();
        display.getSize(point1);
        display.getRealSize(point2);
        result = (int) (point2.getPointY() - point1.getPointY());
        return result;
    }
}
